package com.yuushya.utils.controller

import com.google.gson.stream.JsonReader
import com.yuushya.collision.CollisionFileCreator
import com.yuushya.datagen.JarCreator
import com.yuushya.datagen.ZipReader
import com.yuushya.datagen.data.PackData
import com.yuushya.datagen.utils.Utils.MOD_ID
import com.yuushya.ui.YuushyaLog
import com.yuushya.utils.FileUtils
import com.yuushya.utils.GsonTools
import jakarta.servlet.http.HttpServletResponse
import org.apache.tomcat.util.http.fileupload.IOUtils
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RequestPart
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
import java.net.URLEncoder
import java.nio.file.Files
import java.util.*
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
import javax.swing.JOptionPane
import kotlin.io.path.exists

@RestController
@RequestMapping("/api")
class AssetsAndDataCreator {
    @PostMapping("/assets-and-data-creator/upload")
    fun upload(
        @RequestPart file: MultipartFile,
        @RequestParam assetsAndData: String,
        @RequestParam collision: String,
        response: HttpServletResponse
    ){

        //获取文件全名
        val fileName = file.originalFilename?:"temp"
        //文件上传路径对象
        val uploadFolder = Files.createTempDirectory("temp")
        //压缩包存储目标文件对象
        val destPath = uploadFolder.resolve("./$fileName");

        //步骤1、把上传的压缩包文件保存到指定压缩包路径
        file.transferTo(destPath)

        //解压目标文件夹对象（压缩文件解压到此文件夹中）
        val extractFolder =  uploadFolder.resolve("./extract").also {
            //判断解压后文件夹是否存在//不存在就创建
            if(!it.exists())  Files.createDirectory(it)
        };

        val zipReader= ZipReader(destPath, extractFolder)
        zipReader.unzip()

        var packData: PackData
        try {
            JsonReader(Files.newBufferedReader(extractFolder.resolve("./pack.mcmeta"))).use { reader ->
                packData = GsonTools.NormalGSON.fromJson(reader, PackData::class.java)
            }
        } catch (e: IOException) {
            packData = PackData()
            YuushyaLog.error(e)
        }
        packData.checkVaild(
            destPath.fileName.toString().replace(".zip", "").replace(".jar", "").lowercase(Locale.getDefault())
                .replace("-", "_".replace(" ", "_").replace(".", "_"))
        )
        val jarCreator = JarCreator(packData, extractFolder, extractFolder)
        if (assetsAndData.toBoolean()) jarCreator.createJson()
        val collisionFileCreator = CollisionFileCreator(extractFolder, extractFolder)
        if (collision.toBoolean()) collisionFileCreator.createJson()
        jarCreator.writeModFile()

        val fileNameNew =  packData.mod.name+"."+ MOD_ID+".jar"
        val downloadFileName = URLEncoder.encode(fileNameNew, "UTF-8")

        // 设置文件下载方式：附件下载
        response.setHeader("Content-Disposition", "attachment;fileName=$downloadFileName");
        response.addHeader("resource-filename", downloadFileName)
        response.setHeader("Access-Control-Expose-Headers","resource-filename");
        response.contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE

        ZipOutputStream(response.outputStream).use {
            it.setMethod(ZipOutputStream.DEFLATED)
            jarCreator.createJar(it)
        }

        Dustbin.throwJunk(uploadFolder)

    }
}